package com.honghu.cloud.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.query.QueryUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honghu.cloud.bean.Goods;
import com.honghu.cloud.code.ResponseCode;
import com.honghu.cloud.common.page.Page;
import com.honghu.cloud.dto.AddressDto;
import com.honghu.cloud.dto.FeignHandleFormDto;
import com.honghu.cloud.dto.OrderFormDto;
import com.honghu.cloud.dto.PaymentDto;
import com.honghu.cloud.dto.StoreDto;
import com.honghu.cloud.dto.UserDto;
import com.honghu.cloud.feign.AccessoryFeignClient;
import com.honghu.cloud.feign.AddressFeignClient;
import com.honghu.cloud.feign.GoodsFeignClient;
import com.honghu.cloud.feign.HandleOrderFormFeignClient;
import com.honghu.cloud.feign.PaymentFeignClient;
import com.honghu.cloud.feign.StoreFeignClient;
import com.honghu.cloud.redis.RedisUtil;
import com.honghu.cloud.service.IGoodsService;
import com.honghu.cloud.service.IGoodsSpecificationService;
import com.honghu.cloud.service.ISeckillGoodsService;
import com.honghu.cloud.utils.CommUtil;
import com.honghu.cloud.utils.QueryTools;
import com.honghu.cloud.utils.SecurityUserHolder;
import com.honghu.cloud.utils.TransportTools;
import com.honghu.cloud.utils.domain.SysMap;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@RestController
@RequestMapping(value = "/secKill")
public class GoodsSeckillController {
	@Autowired
	private TransportTools transportTools;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private AddressFeignClient addressFeignClient;
	@Autowired
	private PaymentFeignClient paymentFeignClient;
	@Autowired
	private AccessoryFeignClient accessoryFeignClient;
	@Autowired
	private HandleOrderFormFeignClient handleOrderFormFeignClient;
	@Autowired
	private StoreFeignClient storeFeignClient;
	
	private static final Logger logger = LoggerFactory.getLogger(GoodsSeckillController.class);
	
	@Autowired
	private ISeckillGoodsService seckillGoodsService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private QueryTools queryTools;
	

	/**
	 * 手机端商品列表(设置秒杀专区, 专区查商品用该接口查询)  后台审核商品通过后, 往honghu_seckill_goods插入数据, 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping({ "/goodsSeckillList" })
	public Map<String, Object> goodsSeckillList(HttpServletRequest request,HttpServletResponse response, @RequestBody JSONObject json) {
		Map<String, Object> result = new HashMap<String, Object>();
		String time = json.optString("time");
		String currentPage = json.optString("currentPage");
		
		Map<String, Object> params = queryTools.getParams(currentPage, null, null);
		//获取时间
		params.put("kill_start_time", time);
		Page<Goods> list = goodsService.list(params);
		result.put("list", list);
		
		return ResponseCode.buildSuccessMap(result);
	}
	

	/**
	 * 商品评价
	 * @param request
	 * @param response
	 * @param goods_id
	 * @param currentPage
	 * @param goods_eva
	 * @return
	 *//*
	@RequestMapping(value="/killGoods")
	public Map<String, Object> killGoods(HttpServletRequest request,
			HttpServletResponse response, @RequestBody JSONObject json) {
		String id = json.optString("id");
		Goods obj = goodsService.selectByPrimaryKey(CommUtil.null2Long(id));
		if(obj == null){
			return ResponseCode.buildCodeMap("10003", "商品不存在", null);
		}
		// 商品图片
		List<AccessoryDto> goods_photos = accessoryFeignClient.getGoodsPhotosByAccessoryId(obj.getId());
		goods_photos.add(0, obj.getGoods_main_photo());
		obj.setGoods_photos(goods_photos);
		
		
		// 查询商品规格集合
		List<GoodsSpecification> goods_specis = goodsSpecificationService.getGoodsIdSpecification(obj.getId());
		// 查询自定义规格
		if (StringUtils.isNotEmpty(obj.getGoods_specs_info()) && goods_specis.size() > 0) {
			List<Map> goods_specs_info = JSON.parseArray(obj.getGoods_specs_info(), Map.class);
			for (GoodsSpecification goods_speci : goods_specis) {
				// Map specs_info = goods_specs_info.stream().filter(o ->o.get("id").toString().equals(goods_speci.getProperties().get(0).getId().toString())).findAny().orElse(null);
				for (Map map : goods_specs_info) {
					List<GoodsSpecProperty> properties = goods_speci.getProperties();
					for (GoodsSpecProperty goodsSpecProperty : properties) {
						if (map.get("id").equals(goodsSpecProperty.getId().toString())) {
							goodsSpecProperty.setValue(map.get("name").toString());
						}
					}

				}
			}
		}
		obj.setGoods_specis(goods_specis);
		
		
		Map<String, Object> result = new HashMap<String, Object>();
		String d = "2021-9-1 17:14:00";
		String f = "2021-9-1 20:00:00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date parse = sdf.parse(d);
			Date parse2 = sdf.parse(f);
			obj.setSeckill_start_time(parse);
			obj.setSeckill_end_time(parse2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		         // 调用parse()方法，将字符串转换为日期
		result.put("goods_id", id);
		result.put("obj", obj);
		
		return ResponseCode.buildSuccessMap(result);
	}
	*/
	
	
	
	/**
	 * 手机端商品详情(设置秒杀专区, 专区查商品用该接口查询)
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping({ "/goodsSeckillItems" })
	public Map<String, Object> items(HttpServletRequest request, HttpServletResponse response,
			@RequestBody JSONObject json) {
		Map<String, Object> result = new HashMap<String, Object>();
		String id = json.optString("id");
		// 从redis直接读商品数据
		Object obj =  redisUtil.get("goods_" + id);
		Goods goods=(Goods) obj;
		if (goods == null) {
			return ResponseCode.buildCodeMap("10003", "商品不存在", null);
		}
		result.put("goods_id", id);
		result.put("obj", goods);

		// 查询预约, 用户是否预约

		return ResponseCode.buildSuccessMap(result);
	}
	/**
	 * 商品查看评论
	 */
	
	
	
	
	
	
	//拼团商品 购物车 第一步
	
		/**
		 * 移动端用户对选定购物车进行结算
		 * 拼团商品使用,  获取商品价格 (type判断是否直接购买, )后台算好    ,运费,优惠券列表 ,
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping({ "/add_kill_goods" })
		public Map<String, Object> add_kill_goods(HttpServletRequest request, @RequestBody JSONObject json) {
			String goods_id = json.optString("goods_id"); // 商品id
			String gsp = json.optString("gsp"); // 商品规格
			//String count = json.optString("count"); // 商品数量

			Map<String, Object> result = new HashMap<String, Object>();

			// 获取用户的购物车
			UserDto user = SecurityUserHolder.getCurrentUser(request);

			Goods goods = (Goods) redisUtil.get("goods_"+goods_id);
			if(goods==null){
				 goods = goodsService.selectByPrimaryKey(CommUtil.null2Long(goods_id));
			}
			UserDto currentUser = SecurityUserHolder.getCurrentUser(request);
			if(currentUser.getStore_id()!=null&&currentUser.getStore_id().equals(goods.getGoods_store_id())){
				return ResponseCode.buildFailMap("无法购买自己商品", null);
			}
			
			// 商品价格
			double goods_price = 0.0D;
			goods_price = CommUtil.null2Double(goods.getStore_price());
			if ("spec".equals(goods.getInventory_type())) {
				List<HashMap> list = JSON.parseArray(goods.getGoods_inventory_detail(), HashMap.class);
				String[] gsp_ids = gsp.split(",");
				for (Map temp1 : list) {
					String[] temp_ids = CommUtil.null2String(temp1.get("id")).split("_");
					Arrays.sort(gsp_ids);
					Arrays.sort(temp_ids);
					if (Arrays.equals(gsp_ids, temp_ids)) {
						goods_price = CommUtil.null2Double(temp1.get("price"));
					}
				}
			}
			double price= goods_price;
			List<SysMap> query_cart_all = transportTools.query_pin_goods_trans(goods, new BigDecimal(price),null);
			result.put("all_list", query_cart_all);
			result.put("user", user);
			result.put("goods_price", goods_price);
			result.put("price", price);
			result.put("count", 1);
			result.put("goods", goods);
			result.put("store_id", goods.getGoods_store_id());
			StoreDto storeDto = storeFeignClient.selectByPrimaryKey(goods.getGoods_store_id());
			result.put("store_name",storeDto.getStore_name());

			return ResponseCode.buildSuccessMap(result);
		}
	
	
	
	
	
	
	/**
	 * 预约功能()
	 */
	
	/**
	 * 抢购商品
	 */
	@RequestMapping({ "/goodsSeckill" })
	public Map<String, Object> goodsSeckill(HttpServletRequest request, HttpServletResponse response,
			/*@RequestBody JSONObject json,*/String goods_id ,String gsp) {
		//Map<String, Object> result = new HashMap<String, Object>();
		/*String goods_id = json.optString("goods_id");
		String gsp = json.optString("gsp");*/
		Long currentUserId = SecurityUserHolder.getCurrentUserId(request);
		
		int secKill = seckillGoodsService.secKill(currentUserId, goods_id,gsp);
		/*if (secKill==0) {//秒杀成功,告知前端调用订单服务
				//mq调用创建订单 (秒杀成功,请稍等...然后跳转订单)  /或则返回前端
		}*/
		//result.put("code", secKill);
		return ResponseCode.buildSuccessMap(secKill);
		/*      调完之后try
		  }catch (Exception e){ return new ResultBean("500",e.getMessage()); }
		 */
	}
	
	
	
	
	/**
	 * 确认购物车第3步秒杀
	 * 
	 * @param request
	 * @param store_id
	 *            店铺id
	 * @param addr_id
	 *            地址id
	 * @param gcs
	 *            购物车ids组
	 * @param delivery_time
	 *            配送时间
	 * @param delivery_type
	 *            配送方式
	 * @param delivery_id
	 * @param payType
	 *            支付方式
	 * @param gifts
	 *            赠品id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/kill_goods_cart", method = RequestMethod.POST)
	public Map<String, Object> kill_goods_cart(HttpServletRequest request, String store_id, Long addr_id,
			 String delivery_time, String delivery_type, String delivery_id, String payType, String gifts,
			String order_type ,Integer invoiceType, String invoice,Long goods_id,String gsp,int count) throws Exception {
		
		// TODO 获取用户的购物车
		UserDto currentUser = SecurityUserHolder.getCurrentUser(request);
		if (null == currentUser || null == currentUser.getId()) {
			return ResponseCode.buildEnumMap(ResponseCode.USER_NOT_EXISTS_ERROR, null);
		}
		
	/*	// 获取秒杀活动的商品ID
		String key = "seckill:" + goods_id + ";gsp:" + gsp;
		//先移除元素
		Long leftPop = (Long) redisUtil.leftPop(key);
		if (leftPop != null) {

			// 说明还有商品未被抢购
			String userKey = "seckill:user:" + goods_id;
			// 判断当前用户是否已经抢购过
			boolean opsForSet = redisUtil.opsForSet(userKey, currentUser.getId() + "");
			if (opsForSet) {
				// 将商品信息重新放回到抢购的队列中
				redisUtil.rightPush(key, goods.getId() + "");
			}}*/
		// 前端传入的coupon_32 transport_32 msg_32 coupon_[数字] 的取取值
		Map<String, String> coupon_transport_msg_idsMap = new HashMap<String, String>();

		int max_size = request.getParameterMap().keySet().size();
		String[] coupon_ids = new String[max_size];
		String[] transport_ids = new String[max_size];
		String[] msg_ids = new String[max_size];
		Enumeration pNames = request.getParameterNames();
		int temp_j = 0;
		while (pNames.hasMoreElements()) {
			String name = (String) pNames.nextElement();
			//coupon_id_self: 271
			if (name.indexOf("coupon_") >= 0) {
				coupon_ids[temp_j] = name; //name=coupon_id_self
				coupon_transport_msg_idsMap.put(name, request.getParameter(name));
			}
			//transport_self: 商家承担
			if (name.indexOf("transport_") >= 0) {
				transport_ids[temp_j] = name;
				coupon_transport_msg_idsMap.put(name, request.getParameter(name));
			}
			//msg_self: 
			if (name.indexOf("msg_") >= 0) {
				msg_ids[temp_j] = name;
				coupon_transport_msg_idsMap.put(name, request.getParameter(name));
			}
			temp_j++;
		}

		Map<String, Object> result = new HashMap<String, Object>();
		Goods goods = goodsService.selectByPrimaryKey(goods_id);
		if (goods==null) {
			return ResponseCode.buildCodeMap("10024", "订单中商品有误，请重新下单", null);
		}
		FeignHandleFormDto feignHandleFormDto = new FeignHandleFormDto();
		// 店铺id组
		feignHandleFormDto.setStore_id(goods.getGoods_store_id()+"");
		// 购物车id组
		feignHandleFormDto.setGsp(gsp);
		feignHandleFormDto.setCount(count);
		// 配送时间
		feignHandleFormDto.setDelivery_time(delivery_time);
		// 配送方式
		feignHandleFormDto.setDelivery_type(delivery_type);
		// 自提点id
		feignHandleFormDto.setDelivery_id(delivery_id);
		feignHandleFormDto.setGoods_id(goods_id);
		// 付款方式
		feignHandleFormDto.setPayType(payType);
		// 用户id
		feignHandleFormDto.setUser_id(currentUser.getId());
		// 地址id
		feignHandleFormDto.setAddr_id(addr_id+"");
		// 下单方式
		feignHandleFormDto.setOrder_type(order_type);
		feignHandleFormDto.setCoupon_ids(coupon_ids);
		feignHandleFormDto.setTransport_ids(transport_ids);
		feignHandleFormDto.setMsg_ids(msg_ids);
		//发票信息
		feignHandleFormDto.setInvoiceType(invoiceType);
		feignHandleFormDto.setInvoice(invoice);
		feignHandleFormDto.setCoupon_transport_msg_idsMap(coupon_transport_msg_idsMap);

		
		AddressDto addr = addressFeignClient.selectByPrimaryKey(CommUtil.null2Long(addr_id));
		if (addr == null) {
			return ResponseCode.buildCodeMap("10027", "订单收货地址信息错误", null);
		}

		OrderFormDto main_order = handleOrderFormFeignClient.submitOrderFormKill(feignHandleFormDto);
		result.put("all_of_price",main_order.getTotalPrice());
		
		result.put("user", currentUser);
		result.put("from", "goodsCart");
		result.put("order", main_order);
	
		List<PaymentDto> payments = Lists.newArrayList();
		Map<String, Object> params = Maps.newHashMap();
		params.put("mark", "wx_pay");

		payments = paymentFeignClient.queryPageList(params);

		PaymentDto payment = null;
		if (payments.size() > 0) {
			payment = payments.get(0);
			result.put("appid", payment.getWx_appid());
		}
		return ResponseCode.buildSuccessMap(result);
	}
	
	
	
	
	/**
	 * 用户查看
	 */
	
	
	
	
	
	
}
